package com.bzframework.pro.manager;

import cn.hutool.json.JSONUtil;
import com.bzframework.pro.constant.CommonSqlConstants;
import com.bzframework.pro.entity.*;
import com.bzframework.pro.enums.*;
import com.bzframework.pro.constant.CommonConstants;
import com.bzframework.pro.model.charge.Charge;
import com.bzframework.pro.model.order.OrderRequest;
import com.bzframework.pro.model.order.Product;
import com.bzframework.pro.model.school.SingleCustomerResponse;
import com.bzframework.pro.model.school.customer.SaleChannel;
import com.bzframework.pro.model.school.customer.SalePerson;
import com.bzframework.pro.model.school.employee.EmployeeResponse;
import com.bzframework.pro.model.school.token.AccessToken;
import com.bzframework.pro.model.tanma.TanMaResponse;
import com.bzframework.pro.model.tanma.communicate.CollaboratorRequest;
import com.bzframework.pro.model.tanma.communicate.CommunicationRecordRequest;
import com.bzframework.pro.model.tanma.communicate.CommunicationSqlResult;
import com.bzframework.pro.model.tanma.customer.CustomerImportRequest;
import com.bzframework.pro.model.tanma.customer.CustomerPageData;
import com.bzframework.pro.service.*;
import com.bzframework.pro.utils.ChannelUtils;
import com.bzframework.pro.utils.DateFormatterUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hswebframework.ezorm.rdb.operator.dml.query.SortOrder;
import org.hswebframework.web.bean.FastBeanCopier;
import org.hswebframework.web.crud.query.QueryHelper;
import org.hswebframework.web.id.IDGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.retry.Retry;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * @Author bingzhong
 * @Date 2025/4/7 15:15
 * @Description 生产环境导入流程管理
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ProduceEnvironmentManager {


    private final CustomerService customerService;

    private final HttpService httpService;

    private final EmployeeService employeeService;

    private final SaleChannelService saleChannelService;

    private final CampusService campusService;

    private final OrderService orderService;

    private final QueryHelper queryHelper;

    private final CourseService courseService;

    private final ChargeService chargeService;

    String accessToken = "82d03aab24009fc2bdcb7426d2902fd6a85fa690";



    public void testMappingSalesPersonIdByEmployeeId() {

        AtomicLong res = new AtomicLong(0);

        Mono.zip(
                    customerService.createQuery()
                                   .fetch()
                                   .collectList(),
                    employeeService.createQuery()
                                   .where(EmployeeEntity::getDeleted, 0)
                                   .fetch()
                                   .collectList()
            )
            .flatMapMany(tuple2 -> {
                List<CustomerEntity> customerEntityList = tuple2.getT1();
                List<EmployeeEntity> employeeEntities = tuple2.getT2();
                return Flux.fromIterable(customerEntityList)
                           .map(entity -> {
                               String salePersonId = entity.getSale_person_id();

                               EmployeeEntity employee = employeeEntities
                                       .stream()
                                       .filter(employeeEntity -> employeeEntity.getEmployeeId() != null)
                                       .filter(employeeEntity -> employeeEntity
                                               .getEmployeeId()
                                               .equals(salePersonId))
                                       .findFirst()
                                       .orElse(null);

                               if (employee == null) {
                                   return entity;
                               }
                               // 企微id qwUserId
                               entity.setTanma_sale_person_id(employee.getSalesId());
                               return entity;
                           });
            })
            .buffer(3000)
            .concatMap(entities -> {
                log.info("正在处理数据:{}", entities.size());
                res.getAndAdd(entities.size());
                return customerService.save(entities);
            },1)
            .then()
            .block();

        log.info("数据总条数:{}", res.get());

    }


    public void testBuildCustomerFieldMapping() {
        String buildCustomerFieldMappingUri = "/api/v3/profile-fields/map";
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("fieldId", 167453);
        bodyMap.put("alias", "descriptionTest");
        String bodyStr = JSONUtil.toJsonStr(bodyMap);
        httpService
                .postForTanMaTest(buildCustomerFieldMappingUri, bodyStr, TanMaResponse.class)
                .doOnNext(response -> {
                    System.out.println("response = " + response);
                })
                .block();
    }

    public void testImportCustomer() {
        String uri = "/api/v3/import-customer";

        // 企微员工id 赵思晗
//        String qwUserId = "woJEYhCQAAkKHfcO9ROwdBcsmV-P1tVQ";

        // ======================================================
        // todo 常熟校
//        String campusId = "fc540af1-038e-4614-bf0e-cd3ab437730d";
        // 黄昊星 常熟校区
//        String qwUserId = "woJEYhCQAAv7fzsCopOatgUgUKbjBRng";
        // ======================================================
        // todo 北雅国际教育-龙湖校
//        String campusId = "05d743fd-bed4-45ad-9bcd-a7685bc829ed";
        // 李铭杰 北雅国际教育-龙湖校
//        String qwUserId = "woJEYhCQAAp1oofbvH7jvt6Ma5r5ULnA";
        // ======================================================
        // todo 北雅国际教育-市区校
//        String campusId = "77542ad3-abf7-4d82-a2a2-53aaab228675";
        // Ashley 北雅国际教育-市区校
//        String qwUserId = "woJEYhCQAAiEfytyllwMC-p8Li2lNysQ";
        // ======================================================

        // todo 北雅国际教育-尼盛校
//        String campusId = "7adf4f36-f871-41d5-902f-efb0f2ab38f9";
        // Stella 王鹏 北雅国际教育-市区校
//        String qwUserId = "woJEYhCQAAhHV3WWu9cwY2tTeyPdn2rA";
        // ======================================================

//        // todo 北雅国际教育-新光校
//        String campusId = "55950eda-e3b7-417d-a602-bfe4c0308963";
//        // 管洁 北雅国际教育-新光校
//        String qwUserId = "woJEYhCQAA0dW1Taop063hanMwKUqJkg";
        // ======================================================

        // todo 北雅国际教育-张家港
//        String campusId = "c257468f-5b28-4aad-918e-3dd03f01c7cc";
        // 高阳 北雅国际教育-张家港
//        String qwUserId = "woJEYhCQAAd6sdvJlNTSkBFAbXzMUP9g";
        // ======================================================

        // todo 北雅国际教育-资源库
        String campusId = "edb2b20d-1d49-4270-86c0-b4d1f7e48638";
        // 北雅国际教育-资源库 赵思涵
        String qwUserId = "woJEYhCQAAkKHfcO9ROwdBcsmV-P1tVQ";
        // ======================================================

        Mono.zip(
                saleChannelService.createQuery()
                                  .fetch()
                                  .collectMap(SaleChannelEntity::getId, saleChannelEntity -> saleChannelEntity),

                customerService
                        .createQuery()
                        .where(CustomerEntity::getCampus_id, campusId)
//                        .isNull(CustomerEntity::getTanMaCustomerId)
//                        .and(CustomerEntity::getTanma_sale_person_id, "woJEYhCQAAkKHfcO9ROwdBcsmV-P1tVQ")
//                        .where(CustomerEntity::getId, "013fcfe3-1982-49ec-9092-425b93052586")
                        .where(CustomerEntity::getStatus, 1)
//                        .paging(0, 10)
//                        .like(CustomerEntity::getSale_person_name, "赵思晗")
                        .fetch()
//                        .filter(entity -> Long.parseLong(entity.getCreatetime()) < 20210101000000L)
                        .collectList(),
                campusService.createQuery()
                        .where(CampusEntity::getIscampus, 1)
                        .fetch()
                        .collectMap(CampusEntity::getId, CampusEntity::getName)

        ).flatMapMany(tuple3 -> {

            Map<String, SaleChannelEntity> channelMap = tuple3.getT1();
            List<CustomerEntity> customerEntities = tuple3.getT2();
                Map<String, String> campusIdMap = tuple3.getT3();
                return Flux.fromIterable(customerEntities)
                       .parallel(10)
                       .runOn(Schedulers.parallel())
                       .map(customerEntity -> {

                           List<CustomerImportRequest.Field> fields = new ArrayList<>();

                           String name = customerEntity.getName();
                           CustomerImportRequest.Field customerName = CustomerImportRequest.Field.of("name_produce", Collections.singletonList(name));
                           fields.add(customerName);

                           String smstel = customerEntity.getSmstel();
                           String father_tel = customerEntity.getFather_tel();
                           String mother_tel = customerEntity.getMother_tel();
                           Set<String> telSet = new HashSet<>();
                           if (StringUtils.isNotEmpty(smstel)) {
                               telSet.add(smstel);
                           }
                           if (StringUtils.isNotEmpty(father_tel)) {
                               telSet.add(father_tel);
                           }
                           if (StringUtils.isNotEmpty(mother_tel)) {
                               telSet.add(mother_tel);
                           }
                           CustomerImportRequest.Field mobile = CustomerImportRequest.Field.of("phone_produce", new ArrayList<>(telSet));
                           fields.add(mobile);

                           Integer sex = customerEntity.getSex();
                           String gender = GenderEnum.of(String.valueOf(sex)).getName();
                           CustomerImportRequest.Field sexTest = CustomerImportRequest.Field.of("gender_produce", Collections.singletonList(gender));
                           fields.add(sexTest);

                           String fulltimeSchool = customerEntity.getFulltime_school();
                           CustomerImportRequest.Field fulltimeSchoolField = CustomerImportRequest.Field.of("school_produce", Collections.singletonList(String.valueOf(fulltimeSchool)));
                           fields.add(fulltimeSchoolField);

                           Integer grade_code = customerEntity.getGrade_code();
                           // 要根据时间来计算年级
                           grade_code = DateFormatterUtils.calGrade(customerEntity.getInputDate(), grade_code);
                           String gradeName = GradeEnum.of(grade_code).getName();
                           CustomerImportRequest.Field gradeTest = CustomerImportRequest.Field.of("grade_produce", Collections.singletonList(gradeName));
                           fields.add(gradeTest);

                           // 有效性判定
                           String effectiveness = customerEntity.getValid();
                           EffectivenessEnum effectiveNameEnum = EffectivenessEnum.of(effectiveness);
                           if (effectiveNameEnum != null) {
                               CustomerImportRequest.Field effectivenessTest = CustomerImportRequest.Field.of("valid_produce", Collections.singletonList(effectiveNameEnum.getName()));
                               fields.add(effectivenessTest);
                           }

                           // 校区
                           String campus_id = customerEntity.getCampus_id();
                           String campusName = campusIdMap.getOrDefault(campus_id, "");
                           if (StringUtils.isNotEmpty(campusName)) {
                               // 新光校区单独改名字
                               if ("55950eda-e3b7-417d-a602-bfe4c0308963".equals(campus_id)) {
                                   campusName = "北雅国际教育-久光校";
                               }
                               // 资源库单独改名字
                               if ("edb2b20d-1d49-4270-86c0-b4d1f7e48638".equals(campus_id)) {
                                   campusName = "北雅国际教育-资源库";
                               }
                               List<String> campusNameList = Collections.singletonList(campusName);
                               CustomerImportRequest.Field campusIdTest = CustomerImportRequest.Field.of("campus_produce", campusNameList);
                               fields.add(campusIdTest);
                           }

                           // 招生来源
                           List<SaleChannel> saleChannelList = customerEntity.getSale_channel_list();
                           if (saleChannelList != null && !saleChannelList.isEmpty()) {
                               SaleChannel saleChannel = saleChannelList.get(0);
                               SaleChannelEntity channel = channelMap.getOrDefault(saleChannel.getSale_channel_id(), null);

                               if (channel != null && channel.getItemId() != null) {
                                   // 2级
                                   String miniItemId = channel.getItemId();
                                   String cascadeId = channel.getCascadeId();
                                   // 1级
                                   ChannelUtils.ChannelItem channelItem = ChannelUtils.getChannel(cascadeId);
                                   if (channelItem.getLevel1() == null) {
                                       // 匹配不到自动使用失效来源
                                       CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList("310"));
                                       fields.add(sourceField);
                                   }else {
                                       if (channelItem.isIzLevel2()) {
                                           CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList(channelItem.getLevel1(), miniItemId));
                                           fields.add(sourceField);
                                       }else {
                                           CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList(channelItem.getLevel1(),channelItem.getLevel2(), miniItemId));
                                           fields.add(sourceField);
                                       }

                                   }

                               }

                           }

                           String describe = customerEntity.getDescribe();
                           CustomerImportRequest.Field describeTest = CustomerImportRequest.Field.of("remark_produce", Collections.singletonList(describe));
                           fields.add(describeTest);

                           String customer_id = customerEntity.getCustomer_id();
                           CustomerImportRequest.Field schoolCustomerId = CustomerImportRequest.Field.of("customer_id_produce", Collections.singletonList(customer_id));
                           fields.add(schoolCustomerId);

                           // 客户导入时间
                           String importTime = customerEntity.getInputDate();
                           importTime = DateFormatterUtils.format(importTime);
                           CustomerImportRequest.Field importTimeField = CustomerImportRequest.Field.of("import_time_produce", Collections.singletonList(importTime));
                           fields.add(importTimeField);

                           // 话单属性
                           List<SalePerson> salePersonList = customerEntity.getSale_person_list();
                           // 协作人里存在 赵思涵 添加话单属性
                           String employeeId = "c344286c-8fda-469c-84fd-475a039ed25d";
                           if (salePersonList.stream().anyMatch(customer -> employeeId.equals(customer.getUser_id()))) {
                               CustomerImportRequest.Field oldCallField = CustomerImportRequest.Field.of("old_call_produce", Collections.singletonList("未筛选old call"));
                               fields.add(oldCallField);
                           }

                           // 资源属性
                           String resource = customerEntity.getField3();
                           if (StringUtils.isNotEmpty(resource)) {
                               CustomerImportRequest.Field resourceField = CustomerImportRequest.Field.of("resource_produce", Collections.singletonList(resource));
                               fields.add(resourceField);
                           }
                           String qwUserIdTanMa = customerEntity.getTanma_sale_person_id();

                           // 单独处理属性库
                           List<String> resourceUserId = Arrays.asList("woJEYhCQAAlnURPXJ-n-BMCVoNS6H3VQ", "woJEYhCQAARYMqLYIgNwaOFqVMkQ6Bvg", "woJEYhCQAAr9_3vIKwaFYw0ijenAJDvw", "woJEYhCQAAnuYw-dtiPIPiLbP6m5pT5g");
                           if ("edb2b20d-1d49-4270-86c0-b4d1f7e48638".equals(campus_id)) {
                               String finalQwUserIdTanMa = qwUserIdTanMa;
                               if (resourceUserId.stream().noneMatch(res -> res.equals(finalQwUserIdTanMa))) {
                                   qwUserIdTanMa = qwUserId;
                               }
                           }else {
                               if (StringUtils.isEmpty(qwUserIdTanMa)) {
                                   qwUserIdTanMa = qwUserId;
                               }
                           }

                           CustomerImportRequest request = CustomerImportRequest.of(null, null, qwUserIdTanMa,null, fields);
                           return JSONUtil.toJsonStr(request);
                       })
//                       .doOnNext(customerImportRequest -> {
//                           log.info("线程id: {}, customerImportRequest = {}", Thread
//                                   .currentThread()
//                                   .getName(), customerImportRequest);
//                       })
                       .sequential()
                       .flatMap(bodyStr -> {
                           return httpService.postForTanMaProduce(uri, bodyStr, TanMaResponse.class)
                                             .doOnNext(response -> {
                                                 Integer code = response.getCode();
                                                 if (code != 0) {
                                                     log.error("客户导入失败, 错误信息: {}", JSONUtil.toJsonStr(response));
                                                 }else {
//                                                     log.info("response = {}", JSONUtil.toJsonStr(response));
                                                 }
                                             });
                       }, 10);
        })
                .collectList()
                .doOnNext(list -> {
                    log.info("一共导入：{}", list.size());
                })
            .block();

//        customerService
//                .createQuery()
//                .like(CustomerEntity::getSale_person_name, "赵思晗")
//                .fetch()
//                .filter(entity -> Long.parseLong(entity.getCreatetime()) < 20210101000000L)
//                .collectList()
//                .flatMapMany(Flux::fromIterable)
//                .parallel(10)
//                .runOn(Schedulers.parallel())
//                .map(customerEntity -> {
//
//                    String name = customerEntity.getName();
//                    CustomerImportRequest.Field customerName = CustomerImportRequest.Field.of("name_produce", Collections.singletonList(name));
////                    CustomerImportRequest.Field customerNameTest = CustomerImportRequest.Field.of("customerNameTest", Collections.singletonList(name));
//                    String smstel = customerEntity.getSmstel();
//                    String father_tel = customerEntity.getFather_tel();
//                    String mother_tel = customerEntity.getMother_tel();
//                    Set<String> telSet = new HashSet<>();
//                    if (StringUtils.isNotEmpty(smstel)) {
//                        telSet.add(smstel);
//                    }
//                    if (StringUtils.isNotEmpty(father_tel)) {
//                        telSet.add(father_tel);
//                    }
//                    if (StringUtils.isNotEmpty(mother_tel)) {
//                        telSet.add(mother_tel);
//                    }
//                    CustomerImportRequest.Field mobile = CustomerImportRequest.Field.of("phone_produce", new ArrayList<>(telSet));
////                    CustomerImportRequest.Field mobileTest = CustomerImportRequest.Field.of("mobileTest", Collections.singletonList(smstel));
//
//                    Integer sex = customerEntity.getSex();
//                    String gender = GenderEnum.of(String.valueOf(sex)).getName();
//                    CustomerImportRequest.Field sexTest = CustomerImportRequest.Field.of("gender_produce", Collections.singletonList(gender));
//
//                    String fulltimeSchool = customerEntity.getFulltime_school();
//                    CustomerImportRequest.Field fulltimeSchoolField = CustomerImportRequest.Field.of("school_produce", Collections.singletonList(String.valueOf(fulltimeSchool)));
//
//                    Integer grade_code = customerEntity.getGrade_code();
//                    CustomerImportRequest.Field gradeTest = CustomerImportRequest.Field.of("grade_produce", Collections.singletonList(String.valueOf(grade_code)));
//
//                    String effectiveness = customerEntity.getEffectiveness();
//                    CustomerImportRequest.Field effectivenessTest = CustomerImportRequest.Field.of("valid_produce", Collections.singletonList(effectiveness));
//
//                    String campus_id = customerEntity.getCampus_id();
//                    CustomerImportRequest.Field campusIdTest = CustomerImportRequest.Field.of("campus_produce", Collections.singletonList(campus_id));
//
//                    String sale_channel_id = customerEntity.getSale_channel_id();
//                    CustomerImportRequest.Field saleChannelIdTest = CustomerImportRequest.Field.of("source_produce", Collections.singletonList(sale_channel_id));
//
//                    // 负责人
////                    String sale_person_id = customerEntity.getSale_person_id();
////                    CustomerImportRequest.Field salePersonTest = CustomerImportRequest.Field.of("salePersonTest", Collections.singletonList(sale_person_id));
//
//                    String describe = customerEntity.getDescribe();
//                    CustomerImportRequest.Field describeTest = CustomerImportRequest.Field.of("remark_produce", Collections.singletonList(describe));
//
////                    Integer transfer_status = customerEntity.getTransfer_status();
////                    CustomerImportRequest.Field customerStage = CustomerImportRequest.Field.of("stage_produce", Collections.singletonList(String.valueOf(transfer_status)));
//
//                    String customer_id = customerEntity.getCustomer_id();
//                    CustomerImportRequest.Field schoolCustomerId = CustomerImportRequest.Field.of("customer_id_produce", Collections.singletonList(customer_id));
//
//                    String importTime = customerEntity.getImport_time();
//                    importTime = DateFormatterUtils.format(importTime);
//                    CustomerImportRequest.Field importTimeField = CustomerImportRequest.Field.of("import_time_produce", Collections.singletonList(importTime));
//
//                    String qwUserIdTanMa = customerEntity.getTanma_sale_person_id();
//                    if (StringUtils.isEmpty(qwUserIdTanMa)) {
//                        qwUserIdTanMa = qwUserId;
//                    }
//
//                    CustomerImportRequest request = CustomerImportRequest.of(qwUserIdTanMa, Arrays.asList(customerName, mobile, sexTest, gradeTest, fulltimeSchoolField, effectivenessTest, campusIdTest, saleChannelIdTest, describeTest, schoolCustomerId, importTimeField));
////                    CustomerImportRequest request = CustomerImportRequest.of(qwUserId, Arrays.asList(customerName, customerNameTest, mobile, mobileTest, sexTest, gradeTest, effectivenessTest, campusIdTest, saleChannelIdTest));
//                    return JSONUtil.toJsonStr(request);
//                })
//                .doOnNext(customerImportRequest -> {
//                    log.info("线程id: {}, customerImportRequest = {}", Thread
//                            .currentThread()
//                            .getName(), customerImportRequest);
//                })
//                .sequential()
//                .flatMap(bodyStr -> {
//                    return httpService.postForTanMaProduce(uri, bodyStr, TanMaResponse.class)
//                                      .doOnNext(response -> {
//                                          Integer code = response.getCode();
//                                          if (code != 0) {
//                                              log.error("客户导入失败, 错误信息: {}", JSONUtil.toJsonStr(response));
//                                          }
////                                          log.info("response = {}", JSONUtil.toJsonStr(response));
//                                      });
//                }, 10)
//                .then()
//                .block();
    }

    public void mappingEmployeeIdByName() {


        Mono.zip(
                    employeeService.createQuery()
                                   .where(EmployeeEntity::getDeleted, "0")
                                   .fetch()
                                   .collectList(),
                    httpService.fetchSchoolAccessToken()
            ).flatMapMany(tuple2 -> {

                List<EmployeeEntity> employeeEntityList = tuple2.getT1();
                AccessToken accessToken = tuple2.getT2();

                return Flux.range(1, 13)
                           .parallel(10)
                           .runOn(Schedulers.parallel())
                           .flatMap(offset -> {
                               log.info("线程id:{},offset:{}", Thread.currentThread().getName(), offset);
                               return customerService.fetchEmployeeDataBatch(accessToken.getAccess_token(), offset)
                                                     .flatMapMany(response -> {
                                                         return Flux.fromIterable(JSONUtil.toList(JSONUtil.toJsonStr(response.getData()), EmployeeResponse.class));
                                                     });
                           })
                           .sequential()
                           .collectList()
                           .flatMapMany(employeeResponses -> {
                               return Flux.fromIterable(employeeEntityList)
                                          .flatMap(employeeEntity -> {
                                              String name = employeeEntity.getName();
                                              String id = employeeEntity.getId();
                                              String employeeId = employeeResponses
                                                      .stream()
                                                      // 1 在职员工
                                                      .filter(employeeResponse -> 1 == employeeResponse.getStatus())
                                                      .filter(employeeResponse -> name.equals(employeeResponse.getName()) || name.equals(employeeResponse.getNickname()) || name.contains(employeeResponse.getName()))
                                                      .map(EmployeeResponse::getEmployeeId)
                                                      .findFirst()
                                                      .orElse("");
                                              if (StringUtils.isEmpty(employeeId)) {
                                                  return Mono.empty();
                                              }
                                              employeeEntity.setEmployeeId(employeeId);
                                              return Mono.just(employeeEntity);
                                          });
                           })
                           .buffer(1000)
                           .doOnNext(list -> {
                               log.info("list = {}", list.size());
                           })
                           .flatMap(list -> {
                               log.info("开始更新员工id:{}", list.size());
                               return employeeService.save(list);
                           });
            })
            .then()
            .block();
    }


    /**
     * 导入校管家所有客户`
     */
    public void customerImport() {

        final int totalRecords = 120000;
        final int pageSize = 100;
        final int totalPages = (totalRecords + pageSize - 1) / pageSize; // 计算总页数1200
        final int parallelism = 5; // 并行度
        Flux.range(1, 1200)
            .parallel(parallelism)
            .runOn(Schedulers.boundedElastic())
            .flatMap(pageNo -> {
                log.info("线程id:{},pageNo:{}", Thread.currentThread().getName(), pageNo);
                return customerService
                        .fetchCustomerDataBatch(pageNo, accessToken)
                        .flatMapMany(response -> {
                            // 将每次响应的数据转换为 CustomerEntity 列表
                            Object data = response.getData();
                            String dataJson = JSONUtil.toJsonStr(data);
                            List<CustomerEntity> customerEntityList = JSONUtil.toList(dataJson, CustomerEntity.class);
                            if (customerEntityList.isEmpty()) {
                                return Mono.empty();
                            }
                            customerEntityList = customerEntityList
                                    .stream()
                                    .peek(e -> {
                                        e.setId(e.getCustomer_id());
                                        e.setValid(e.getIsInvalid());
                                    })
                                    .collect(Collectors.toList());
                            return Flux.fromIterable(customerEntityList);
                        });
            }, false, 5)
            .sequential()
//            .collectList()
//            .doOnNext(list -> {
//                log.info("总数据量 = {}", list.size());
//            })
            .buffer(1000)
            .delayElements(Duration.ofMillis(50)) // 添加延迟
            .concatMap(list -> {
                if (list == null || list.isEmpty()) {
                    return Mono.empty();
                }
                log.info("线程id:{},正在导入数据:{}",Thread.currentThread().getName(), list.size());
                return customerService.save(list);
            },1)
            .then()
            .block();

    }


    public void testMappingEmployeeNameBySalesPersonId() {

        // 发生错误的客户id列表
        List<String> errorCustomerIdList = new CopyOnWriteArrayList<>();
        AtomicInteger atomicInteger = new AtomicInteger(0);

        httpService.fetchSchoolAccessToken()
                   .flatMapMany(accessTokenRes -> {
                       String accessToken = accessTokenRes.getAccess_token();
                       return customerService
                               .createQuery()
                               .orderBy(SortOrder.asc(CustomerEntity::getCreatetime))
                               .fetch()
                               .buffer(10000)
                               .parallel(10)
                               .runOn(Schedulers.parallel())
                               .flatMap(customerEntities -> {
                                   atomicInteger.addAndGet(customerEntities.size());
                                   log.info("线程id: {},客户数量: {}", Thread
                                           .currentThread()
                                           .getName(), customerEntities.size());
                                   return Flux.fromIterable(customerEntities)
                                              .flatMap(customer -> {
                                                  // 负责人id
                                                  String salePersonId = customer.getSale_person_id();
                                                  log.info("salePersonId:{}", salePersonId);
                                                  String customerId = customer.getCustomer_id();
                                                  return customerService
                                                          .fetchEmployeeData(salePersonId, accessToken)
                                                          .flatMap(response -> {
                                                              if (response.getErrcode() != 0) {
//                                                                  return Mono.error(new RuntimeException("获取客户信息失败: " + response.getErrmsg() + ", 客户id: " + customerId));
                                                                  errorCustomerIdList.add(customerId);
                                                                  return Mono.empty();
                                                              }
                                                              String name = response.getName();
                                                              CustomerEntity customerEntity = new CustomerEntity();
                                                              customerEntity.setId(customerId);
                                                              customerEntity.setSale_person_name(name);
                                                              return Mono.just(customerEntity);
                                                          })
                                                          .doOnError(e -> {
                                                              errorCustomerIdList.add(customerId);
                                                              log.error("获取客户信息失败: {}, 客户id: {}", e.getMessage(), customerId);
                                                          });
                                              }, 5);
                               })
                               .sequential()
                               .buffer(3000)
                               .concatMap(customerEntities -> {
                                   log.info("线程id:{}, 插入数据:{} ", Thread
                                           .currentThread()
                                           .getName(), customerEntities.size());
                                   return customerService.save(customerEntities);
                               },1);
                   })
                   .then()
                   .block();
        log.info("错误客户id列表: {}", errorCustomerIdList.size());

    }


    public void syncTanMaCustomerIdMapping2Local() {
        String highSeaCustomerUri = "/api/v3/customer/search";

        // ======================================================
        // todo 常熟校
//        String campusId = "fc540af1-038e-4614-bf0e-cd3ab437730d";

        // ======================================================
        // todo 北雅国际教育-龙湖校
//        String campusId = "05d743fd-bed4-45ad-9bcd-a7685bc829ed";

        // todo 北雅国际教育-市区校
//        String campusId = "77542ad3-abf7-4d82-a2a2-53aaab228675";

        // todo 北雅国际教育-尼盛校
//        String campusId = "7adf4f36-f871-41d5-902f-efb0f2ab38f9";

        // todo 北雅国际教育-新光校
//        String campusId = "55950eda-e3b7-417d-a602-bfe4c0308963";
        // ======================================================

        // todo 北雅国际教育-张家港
//        String campusId = "c257468f-5b28-4aad-918e-3dd03f01c7cc";

        // todo 北雅国际教育-资源库
        String campusId = "edb2b20d-1d49-4270-86c0-b4d1f7e48638";
        // ======================================================
        customerService.createQuery()
                       .where(CustomerEntity::getCampus_id, campusId)
//                       .where(CustomerEntity::getCustomer_id, "dcb635f0-8d2c-4cd9-9023-9a56404857d8")
                       .fetch()
                       .flatMap(customerEntity -> {
                           Map<String, Object> bodyMap = new HashMap<>();
                           Map<String, Object> conditionMap = new HashMap<>();
                           conditionMap.put("conditionOp", 0);
                           Map<String, Object> conditionItemMap = new HashMap<>();
                           conditionItemMap.put("name", 168179);
                           conditionItemMap.put("op", 2);
                           conditionItemMap.put("values", Collections.singletonList(customerEntity.getId()));
                           conditionMap.put("conditionItems", Collections.singletonList(conditionItemMap));
                           bodyMap.put("conditions", conditionMap);
                           String bodyStr = JSONUtil.toJsonStr(bodyMap);
                           return httpService.postForTanMaProduce(highSeaCustomerUri, bodyStr, TanMaResponse.class)
                                             .flatMapMany(response -> {
                                                 CustomerPageData customerPageData = JSONUtil.toBean(JSONUtil.toJsonStr(response.getData()), CustomerPageData.class);
                                                 List<Map<String, Object>> dataList = customerPageData.getData();
                                                 if (dataList == null || dataList.isEmpty()) {
                                                     return Mono.empty();
                                                 }
                                                 return Flux.fromIterable(dataList)
                                                            .flatMap(dataMap -> {
                                                                // 校管家id
                                                                String customerId = String.valueOf(dataMap.getOrDefault("168179", ""));
                                                                String tanMaCustomerId = String.valueOf(dataMap.getOrDefault("customerId", ""));
                                                                if (StringUtils.isAnyEmpty(customerId, tanMaCustomerId)) {
                                                                    return Mono.empty();
                                                                }
                                                                CustomerEntity customer = new CustomerEntity();
                                                                customer.setId(customerId);
                                                                customer.setTanMaCustomerId(tanMaCustomerId);
                                                                return Mono.just(customer);
                                                            });

                                             });
                       }, 50)
                       .buffer(3000)
                       .concatMap(converter -> {
                           log.info("线程:{},已处理:{} 条数据 ", Thread.currentThread().getName(), converter.size());
                           return customerService.save(converter);
                       },1)
                   .collectList()
                   .block();
    }


    public void testFetchCustomerMultipleByBatch() {

        // 发生错误的客户id列表
        List<String> errorCustomerIdList = new CopyOnWriteArrayList<>();
        AtomicInteger atomicInteger = new AtomicInteger(0);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        customerService.createQuery()
//                       .orderBy(SortOrder.asc(CustomerEntity::getCreatetime))
                       .fetch()
                       .buffer(10000)
                       .parallel(10)
                       .runOn(Schedulers.parallel())
                       .flatMap(customerEntities -> {
                           atomicInteger.addAndGet(customerEntities.size());
                           log.info("线程id: {},客户数量: {}", Thread
                                   .currentThread()
                                   .getName(), customerEntities.size());
                           return Flux.fromIterable(customerEntities)
                                      .flatMap(customer -> {
                                          String customerId = customer.getCustomer_id();
                                          return fetchCustomerById(customerId)
                                                  .flatMap(response -> {
                                                      if (response.getErrcode() != 0) {
                                                          return Mono.error(new RuntimeException("获取客户信息失败: " + response.getErrmsg() + ", 客户id: " + customerId));
                                                      }
                                                      CustomerEntity customerEntity = FastBeanCopier.copy(response, new CustomerEntity());
                                                      customerEntity.setId(customerId);
                                                      customerEntity.setCustomer_id(customerId);
                                                      return Mono.just(customerEntity);
                                                  })
                                                  .doOnError(e -> {
                                                      errorCustomerIdList.add(customerId);
                                                      log.error("获取客户信息失败: {}, 客户id: {}", e.getMessage(), customerId);
                                                  });
                                      }, 5);
                       })
                       .sequential()
                       .buffer(3000)
                       // 每次执行只更新数据
//                       .map(customerList -> customerList
//                               .stream()
//                               .peek(customer -> customer.setId(customer.getCustomer_id()))
//                               .collect(Collectors.toList()))
                       .concatMap(customerEntities -> {
                           log.info("线程id:{}, 插入数据:{} ", Thread
                                   .currentThread()
                                   .getName(), customerEntities.size());
                           return customerService.save(customerEntities);
                       },1)
                       .collectList()
                       .block();
        stopWatch.stop();
        double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
        log.info("总耗时：{}秒, 总数据量: {}", totalTimeSeconds, atomicInteger.get());
        log.info("错误客户id列表: {}", errorCustomerIdList.size());

    }


    /**
     * 校课堂获取单个客户
     *
     * @param customerId
     * @return
     */
    public Mono<SingleCustomerResponse> fetchCustomerById(String customerId) {
        String singleCustomerUri = "/customer/get_customer";
        return WebClient
                .create(CommonConstants.SCHOOL_HOUSEKEEPER_PRODUCTION_URL)
                .get()
                .uri(uriBuilder -> uriBuilder
                        .path(singleCustomerUri)
                        .queryParam("access_token", accessToken)
                        .queryParam("customer_id", customerId)
                        .build())
                .retrieve()
                .bodyToMono(SingleCustomerResponse.class)
                .timeout(Duration.ofSeconds(15)) // 单独请求超时
                .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))); // 指数退避重试;
    }

    public void testImportCollaborator() {

        String importCommunicateRecordUri = "/api/v3/customer/batchAddShare";

        // todo 常熟校
//        String campusId = "fc540af1-038e-4614-bf0e-cd3ab437730d";
        // 黄昊星 常熟校区
//        String qwUserId = "656053016428288";
        // ======================================================
        // todo 北雅国际教育-龙湖校
//        String campusId = "05d743fd-bed4-45ad-9bcd-a7685bc829ed";
        // 李铭杰 北雅国际教育-龙湖校
//        String qwUserId = "656053016403712";
        // ======================================================
        // todo 北雅国际教育-市区校
//        String campusId = "77542ad3-abf7-4d82-a2a2-53aaab228675";
        // Ashley 北雅国际教育-市区校
//        String qwUserId = "656053016420096";

        // todo 北雅国际教育-尼盛校
//        String campusId = "7adf4f36-f871-41d5-902f-efb0f2ab38f9";
        // Stella 王鹏 北雅国际教育-市区校
//        String qwUserId = "656053016434432";

        // todo 北雅国际教育-新光校
//        String campusId = "55950eda-e3b7-417d-a602-bfe4c0308963";
        // 管洁 北雅国际教育-新光校
//        String qwUserId = "656053016424192";

        // todo 北雅国际教育-张家港
//        String campusId = "c257468f-5b28-4aad-918e-3dd03f01c7cc";
        // 高阳 北雅国际教育-张家港
//        String qwUserId = "656053016413952";
        // ======================================================

        // todo 北雅国际教育-资源库
        String campusId = "edb2b20d-1d49-4270-86c0-b4d1f7e48638";
        // 北雅国际教育-资源库 赵思涵
        String qwUserId = "656053015510784";

        Mono.zip(
                    employeeService.createQuery()
                                   .where(EmployeeEntity::getDeleted, "0")
                                   .fetch()
                                   .collectMap(EmployeeEntity::getEmployeeId, EmployeeEntity::getId),
                    customerService.createQuery()
                                   .where(CustomerEntity::getCampus_id, campusId)
//                                   .and(CustomerEntity::getId, "dcb635f0-8d2c-4cd9-9023-9a56404857d8")
                                   .notNull(CustomerEntity::getTanMaCustomerId)
                                   .fetch()
                                   .collectList()
            ).flatMapMany(tuple2 -> {
                Map<String, String> employeeIdMap = tuple2.getT1();
                List<CustomerEntity> customerEntities = tuple2.getT2();
                return Flux.fromIterable(customerEntities)
                           .flatMap(customerEntity -> {
                               List<SalePerson> salePersonList = customerEntity.getSale_person_list();
                               if (salePersonList.size() == 0) {
                                   return Mono.empty();
                               }
                               // 客户负责人
                               String salePersonId = customerEntity.getSale_person_id();
                               String tanMaSalePersonId = employeeIdMap.getOrDefault(salePersonId, "");
                               if (StringUtils.isEmpty(tanMaSalePersonId)) {
                                   tanMaSalePersonId = qwUserId;
                               }
                               long tanmaSalesId = Long.parseLong(tanMaSalePersonId);

                               String tanMaCustomerId = customerEntity.getTanMaCustomerId();

                               List<Long> userIdList = salePersonList
                                       .stream().map(salePerson -> {
                                           String employeeId = salePerson.getUser_id();
                                           String userId = employeeIdMap.getOrDefault(employeeId, "");
                                           return userId;
                                       })
                                       .filter(StringUtils::isNotBlank)
                                       .map(Long::valueOf)
                                       // TanMaResponse(code=-1, message=不能共享给自己, data=null)
                                       .filter(userId -> userId != tanmaSalesId)
                                       .collect(Collectors.toList());
                               if (userIdList.isEmpty()) {
                                   return Mono.empty();
                               }
//                        List<Long> userIdList = Arrays.asList(659738885701952L);
//                        long salesId = 654819897884864L;
                               return Mono.just(CollaboratorRequest.of(Long.valueOf(tanMaCustomerId), tanmaSalesId, userIdList));
                           });
            })
            .flatMap(requests -> {
                String bodyStr = JSONUtil.toJsonStr(requests);
                log.info("请求体:{}", bodyStr);
                return httpService.postForTanMaProduce(importCommunicateRecordUri, bodyStr, TanMaResponse.class)
                                  .doOnNext(response -> {
                                      if (response.getCode() != 0) {
                                          log.error("response = {}, body:{}", response, bodyStr);
                                      }else {
                                          log.info("response = {}, body:{}", response, bodyStr);
                                      }
                                  });
            }, 10)
            .then()
            .block();

    }


    public Mono<Integer> testImportCommunicateRecord(List<String> ids) {

        List<CommunicationRecordRequest> results = new CopyOnWriteArrayList<>();
        String importCommunicateRecordUri = "/api/v3/customer/follow/add-batch";
        return queryHelper.select(CommonSqlConstants.fetchCommunicationRecord, CommunicationSqlResult::new)
//                   .where(dsl -> dsl.where("bc.id", "0022448e-3768-4929-a1ec-cdd50fb8ab40")
//                                    .notNull("bcr.tan_ma_employee_id"))
                   .where(dsl -> dsl.notNull("bc.tan_ma_customer_id")
                                    .in("bc.id", ids))
                   .fetch()
                   .flatMap(communicationSqlResult -> {
                       String id = communicationSqlResult.getId();
                       String tanMaCustomerId = communicationSqlResult.getTanMaCustomerId();
                       String content = communicationSqlResult.getContent();
                       String createTime = communicationSqlResult.getCreateTime();
                       String salesId = communicationSqlResult.getSalesId();

                       if (StringUtils.isEmpty(salesId)) {
                           return Mono.empty();
//                           return CommunicationRecordRequest.of(Long.valueOf(tanMaCustomerId), 656053015510784L,
//                                                                content, DateFormatterUtils.format(createTime));
                       }
                       CommunicationRecordRequest communicationRecordRequest = CommunicationRecordRequest.of(Long.valueOf(tanMaCustomerId), Long.valueOf(salesId),
                                                                                     content, DateFormatterUtils.format(createTime));
                       return Mono.just(communicationRecordRequest);
                   })
                   .buffer(100)
                   .flatMap(requests -> {
                       results.addAll(requests);
                       log.info("客户ids:{}", requests
                               .stream()
                               .map(CommunicationRecordRequest::getCustomerId)
                               .collect(Collectors.toList()));
                       String bodyStr = JSONUtil.toJsonStr(requests);
                       log.info("请求体:{}", bodyStr);
                       return httpService.postForTanMaProduce(importCommunicateRecordUri, bodyStr, TanMaResponse.class)
                                         .doOnNext(response -> {
                                             log.info("探马返回结果:{}", JSONUtil.toJsonStr(response));
                                         });
                   })
                                  .then(Mono.just(results.size()));
//                   .collectList()
//                   .block();


    }


    public void updateCustomerFields() {

        String uri = "/api/v3/customer/update-by-id";
        // 常熟校
//        String campusId = "fc540af1-038e-4614-bf0e-cd3ab437730d";
        // todo 北雅国际教育-龙湖校
//        String campusId = "05d743fd-bed4-45ad-9bcd-a7685bc829ed";
        // todo 北雅国际教育-市区校
//        String campusId = "77542ad3-abf7-4d82-a2a2-53aaab228675";

        // todo 北雅国际教育-尼盛校
//        String campusId = "7adf4f36-f871-41d5-902f-efb0f2ab38f9";

        // todo 北雅国际教育-新光校
//        String campusId = "55950eda-e3b7-417d-a602-bfe4c0308963";

        // todo 北雅国际教育-张家港
//        String campusId = "c257468f-5b28-4aad-918e-3dd03f01c7cc";

        // todo 北雅国际教育-资源库 待办
        String campusId = "edb2b20d-1d49-4270-86c0-b4d1f7e48638";

        Mono.zip(
                saleChannelService.createQuery()
                                  .fetch()
                                  .collectMap(SaleChannelEntity::getId, saleChannelEntity -> saleChannelEntity),
                customerService
                        .createQuery()
                        .where(CustomerEntity::getCampus_id, campusId)
//                        .where(CustomerEntity::getCustomer_status, "e1498546-6010-48dc-95cf-5d73ed9308f0")
                        .notNull(CustomerEntity::getTanMaCustomerId)
                        .fetch()
                        .collectList(),
                campusService.createQuery()
                             .where(CampusEntity::getIscampus, 1)
                             .fetch()
                             .collectMap(CampusEntity::getId, CampusEntity::getName)

        ).flatMapMany(tuple3 -> {
            Map<String, SaleChannelEntity> channelMap = tuple3.getT1();
            List<CustomerEntity> customerEntities = tuple3.getT2();
            Map<String, String> campusIdMap = tuple3.getT3();
            return Flux.fromIterable(customerEntities)
                    .parallel()
                    .runOn(Schedulers.boundedElastic())
                    .map(customerEntity -> {
                        return buildCustomerRequestBodyStr(campusIdMap, customerEntity, channelMap);
                    })
                       .sequential()
                       .flatMap(body -> {
//                           return Mono.empty();
                           return httpService.postForTanMaProduce(uri, JSONUtil.toJsonStr(body), TanMaResponse.class)
                                             .doOnNext(response -> {
                                                 if (response.getCode() != 0) {
                                                     log.error("探马返回错误:{}", JSONUtil.toJsonStr(response));
                                                 }
//                                                 log.info("response:{}, 请求体:{}", JSONUtil.toJsonStr(response), body);
                                             });
                       },10);
        })

                    .then()
                    .block();




//        customerService
//                .createQuery()
//                .where(CustomerEntity::getCampus_id, campusId)
//                .notNull(CustomerEntity::getTanMaCustomerId)
////                .and(CustomerEntity::getId, "00b14860-9f94-4a4d-81d5-42f9691e3fa5")
////                .where(CustomerEntity::getCampus_id, "fc540af1-038e-4614-bf0e-cd3ab437730d")
////                .and(CustomerEntity::getTanma_sale_person_id, "woJEYhCQAAkKHfcO9ROwdBcsmV-P1tVQ")
////                .notNull(CustomerEntity::getTanMaCustomerId)
////                .where(CustomerEntity::getId, "8efac429-886e-4f3e-a855-3272ac47b11e")
//                .fetch()
//                .flatMap(customerEntity -> {
//
//                    List<CustomerImportRequest.Field> fields = new ArrayList<>();
//
////                    String name = customerEntity.getName();
////                    CustomerImportRequest.Field customerName = CustomerImportRequest.Field.of("name_produce", Collections.singletonList(name));
////                    fields.add(customerName);
////                    CustomerImportRequest.Field customerNameTest = CustomerImportRequest.Field.of("customerNameTest", Collections.singletonList(name));
//
////                    String smstel = customerEntity.getSmstel();
////                    String father_tel = customerEntity.getFather_tel();
////                    String mother_tel = customerEntity.getMother_tel();
////                    Set<String> telSet = new HashSet<>();
////                    if (StringUtils.isNotEmpty(smstel)) {
////                        telSet.add(smstel);
////                    }
////                    if (StringUtils.isNotEmpty(father_tel)) {
////                        telSet.add(father_tel);
////                    }
////                    if (StringUtils.isNotEmpty(mother_tel)) {
////                        telSet.add(mother_tel);
////                    }
////                    CustomerImportRequest.Field mobile = CustomerImportRequest.Field.of("phone_produce", new ArrayList<>(telSet));
////                    fields.add(mobile);
////                    CustomerImportRequest.Field mobileTest = CustomerImportRequest.Field.of("mobileTest", Collections.singletonList(smstel));
//
////                    Integer sex = customerEntity.getSex();
////                    String gender = GenderEnum.of(String.valueOf(sex)).getName();
////                    CustomerImportRequest.Field sexTest = CustomerImportRequest.Field.of("gender_produce", Collections.singletonList(gender));
////                    fields.add(sexTest);
////
////                    String fulltimeSchool = customerEntity.getFulltime_school();
////                    CustomerImportRequest.Field fulltimeSchoolField = CustomerImportRequest.Field.of("school_produce", Collections.singletonList(String.valueOf(fulltimeSchool)));
////                    fields.add(fulltimeSchoolField);
////
////                    Integer grade_code = customerEntity.getGrade_code();
////                    String gradeName = GradeEnum.of(grade_code).getName();
////                    CustomerImportRequest.Field gradeTest = CustomerImportRequest.Field.of("grade_produce", Collections.singletonList(gradeName));
////                    fields.add(gradeTest);
//
//                    // 有效性判定
////                    String effectiveness = customerEntity.getEffectiveness();
////                    String effectiveName = EffectivenessEnum.of(effectiveness).getName();
////                    CustomerImportRequest.Field effectivenessTest = CustomerImportRequest.Field.of("valid_produce", Collections.singletonList(effectiveName));
////                    fields.add(effectivenessTest);
//
////                    // 校区
////                    String campus_id = customerEntity.getCampus_id();
////                    String campusName = campusIdMap.getOrDefault(campus_id, "");
////                    if (StringUtils.isNotEmpty(campusName)) {
////                        List<String> campusNameList = Collections.singletonList(campusName);
////                        CustomerImportRequest.Field campusIdTest = CustomerImportRequest.Field.of("campus_produce", campusNameList);
////                        fields.add(campusIdTest);
////                    }
//
////                           String sale_channel_id = customerEntity.getSale_channel_id();
//                    // 招生来源
////                    List<SaleChannel> saleChannelList = customerEntity.getSale_channel_list();
////                    if (!saleChannelList.isEmpty()) {
////                        List<String> channelNames = saleChannelList.stream()
////                                                                   .map(channel -> channelMap.getOrDefault(channel.getSale_channel_id(),""))
////                                                                   .map(nameField -> {
////                                                                       SourceEnum sourceEnum = SourceEnum.of(nameField);
////                                                                       if (sourceEnum == null || nameField.isEmpty()) {
////                                                                           return "";
////                                                                       }
////                                                                       return String.valueOf(sourceEnum.getItemId());
////                                                                   })
////                                                                   .collect(Collectors.toList());
//////                               CustomerImportRequest.Field saleChannelIdTest = CustomerImportRequest.Field.of("source_produce", channelNames);
//////                               fields.add(saleChannelIdTest);
////                        if (channelNames.stream().anyMatch(String::isEmpty)) {
////                            CustomerImportRequest.Field saleChannelIdTest = CustomerImportRequest.Field.of("source_produce", Arrays.asList(String.valueOf(SourceEnum.invalidSource.getItemId())));
////                            fields.add(saleChannelIdTest);
////                        }else {
////                            CustomerImportRequest.Field saleChannelIdTest = CustomerImportRequest.Field.of("source_produce", channelNames);
////                            fields.add(saleChannelIdTest);
////                        }
////                    }
//
////                    String describe = customerEntity.getDescribe();
////                    CustomerImportRequest.Field describeTest = CustomerImportRequest.Field.of("remark_produce", Collections.singletonList(describe));
////                    fields.add(describeTest);
////
////                    String customer_id = customerEntity.getCustomer_id();
////                    CustomerImportRequest.Field schoolCustomerId = CustomerImportRequest.Field.of("customer_id_produce", Collections.singletonList(customer_id));
////                    fields.add(schoolCustomerId);
////
//
//                    List<SalePerson> salePersonList = customerEntity.getSale_person_list();
//                    // 协作人里存在 赵思涵添加话单属性
//                    if (salePersonList.stream().anyMatch(customer -> "c344286c-8fda-469c-84fd-475a039ed25d".equals(customer.getUser_id()))) {
//                        CustomerImportRequest.Field oldCallField = CustomerImportRequest.Field.of("old_call_produce", Collections.singletonList("未筛选old call"));
//                        fields.add(oldCallField);
//                    }
//
//                    // 客户导入时间
//                    String importTime = customerEntity.getInputDate();
//                    importTime = DateFormatterUtils.format(importTime);
//                    CustomerImportRequest.Field importTimeField = CustomerImportRequest.Field.of("import_time_produce", Collections.singletonList(importTime));
//                    fields.add(importTimeField);
//
//                    // 资源属性
//                    String resource = customerEntity.getField3();
//                    if (StringUtils.isNotEmpty(resource)) {
//                        CustomerImportRequest.Field resourceField = CustomerImportRequest.Field.of("resource_produce", Collections.singletonList(resource));
//                        fields.add(resourceField);
//                    }
//
//                    CustomerImportRequest request = CustomerImportRequest.of(null, customerEntity.getTanMaCustomerId(), fields);
//                    log.info("request: {}", JSONUtil.toJsonStr(request));
//                    return httpService.postForTanMaProduce(uri, JSONUtil.toJsonStr(request), TanMaResponse.class);
////                    return Mono.empty();
//                }, 10)
//                .doOnNext(response -> {
//                    log.info("response = {}", JSONUtil.toJsonStr(response));
//                })
//                .then()
//                .block();


    }

    private static String buildCustomerRequestBodyStr(Map<String, String> campusIdMap, CustomerEntity customerEntity, Map<String, SaleChannelEntity> channelMap) {
        List<CustomerImportRequest.Field> fields = new ArrayList<>();

        String name = customerEntity.getName();
        CustomerImportRequest.Field customerName = CustomerImportRequest.Field.of("name_produce", Collections.singletonList(name));
        fields.add(customerName);

        String smstel = customerEntity.getSmstel();
        String father_tel = customerEntity.getFather_tel();
        String mother_tel = customerEntity.getMother_tel();
        Set<String> telSet = new HashSet<>();
        if (StringUtils.isNotEmpty(smstel)) {
            telSet.add(smstel);
        }
        if (StringUtils.isNotEmpty(father_tel)) {
            telSet.add(father_tel);
        }
        if (StringUtils.isNotEmpty(mother_tel)) {
            telSet.add(mother_tel);
        }
        CustomerImportRequest.Field mobile = CustomerImportRequest.Field.of("phone_produce", new ArrayList<>(telSet));
        fields.add(mobile);

        Integer sex = customerEntity.getSex();
        String gender = GenderEnum.of(String.valueOf(sex)).getName();
        CustomerImportRequest.Field sexTest = CustomerImportRequest.Field.of("gender_produce", Collections.singletonList(gender));
        fields.add(sexTest);

        String fulltimeSchool = customerEntity.getFulltime_school();
        CustomerImportRequest.Field fulltimeSchoolField = CustomerImportRequest.Field.of("school_produce", Collections.singletonList(String.valueOf(fulltimeSchool)));
        fields.add(fulltimeSchoolField);

        Integer grade_code = customerEntity.getGrade_code();
        // 要根据时间来计算年级
        grade_code = DateFormatterUtils.calGrade(customerEntity.getInputDate(), grade_code);
        String gradeName = GradeEnum.of(grade_code).getName();
        CustomerImportRequest.Field gradeTest = CustomerImportRequest.Field.of("grade_produce", Collections.singletonList(gradeName));
        fields.add(gradeTest);

        // 有效性判定
        String effectiveness = customerEntity.getValid();
        EffectivenessEnum effectiveNameEnum = EffectivenessEnum.of(effectiveness);
        if (effectiveNameEnum != null) {
            CustomerImportRequest.Field effectivenessTest = CustomerImportRequest.Field.of("valid_produce", Collections.singletonList(effectiveNameEnum.getName()));
            fields.add(effectivenessTest);
        }

        // 校区
        String campus_id = customerEntity.getCampus_id();
        String campusName = campusIdMap.getOrDefault(campus_id, "");
        if (StringUtils.isNotEmpty(campusName)) {
            // 新光校区单独改名字
            if ("55950eda-e3b7-417d-a602-bfe4c0308963".equals(campus_id)) {
                campusName = "北雅国际教育-久光校";
            }
            // 资源库单独改名字
            if ("edb2b20d-1d49-4270-86c0-b4d1f7e48638".equals(campus_id)) {
                campusName = "北雅国际教育-资源库";
            }
            List<String> campusNameList = Collections.singletonList(campusName);
            CustomerImportRequest.Field campusIdTest = CustomerImportRequest.Field.of("campus_produce", campusNameList);
            fields.add(campusIdTest);
        }

        // 招生来源
        List<SaleChannel> saleChannelList = customerEntity.getSale_channel_list();
        if (saleChannelList != null && !saleChannelList.isEmpty()) {
            SaleChannel saleChannel = saleChannelList.get(0);
            SaleChannelEntity channel = channelMap.getOrDefault(saleChannel.getSale_channel_id(), null);

            if (channel != null && channel.getItemId() != null) {
                // 2级
                String miniItemId = channel.getItemId();
                String cascadeId = channel.getCascadeId();
                // 1级
                ChannelUtils.ChannelItem channelItem = ChannelUtils.getChannel(cascadeId);
                if (channelItem.getLevel1() == null) {
                    // 匹配不到自动使用失效来源
                    CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList("310"));
                    fields.add(sourceField);
                }else {
                    if (channelItem.isIzLevel2()) {
                        CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList(channelItem.getLevel1(), miniItemId));
                        fields.add(sourceField);
                    }else {
                        CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList(channelItem.getLevel1(),channelItem.getLevel2(), miniItemId));
                        fields.add(sourceField);
                    }

                }

            } else {
                CustomerImportRequest.Field sourceField = CustomerImportRequest.Field.of("source_produce", Arrays.asList("310"));
                fields.add(sourceField);
            }

        }

        String describe = customerEntity.getDescribe();
        CustomerImportRequest.Field describeTest = CustomerImportRequest.Field.of("remark_produce", Collections.singletonList(describe));
        fields.add(describeTest);

        String customer_id = customerEntity.getCustomer_id();
        CustomerImportRequest.Field schoolCustomerId = CustomerImportRequest.Field.of("customer_id_produce", Collections.singletonList(customer_id));
        fields.add(schoolCustomerId);

        // 客户导入时间
        String importTime = customerEntity.getInputDate();
        importTime = DateFormatterUtils.format(importTime);
        CustomerImportRequest.Field importTimeField = CustomerImportRequest.Field.of("import_time_produce", Collections.singletonList(importTime));
        fields.add(importTimeField);

        // 话单属性
        List<SalePerson> salePersonList = customerEntity.getSale_person_list();
        // 协作人里存在 赵思涵添加话单属性
        String employeeId = "c344286c-8fda-469c-84fd-475a039ed25d";
        if (salePersonList.stream().anyMatch(customer -> employeeId.equals(customer.getUser_id()))) {
            CustomerImportRequest.Field oldCallField = CustomerImportRequest.Field.of("old_call_produce", Collections.singletonList("未筛选old call"));
            fields.add(oldCallField);
        }else {
            CustomerImportRequest.Field oldCallField = CustomerImportRequest.Field.of("old_call_produce", Collections.singletonList("非old call"));
            fields.add(oldCallField);
        }

        // 资源属性
        String resource = customerEntity.getField3();
        if (StringUtils.isNotEmpty(resource)) {
            CustomerImportRequest.Field resourceField = CustomerImportRequest.Field.of("resource_produce", Collections.singletonList(resource));
            fields.add(resourceField);
        }
        // 旅程id
        String travelId = "656428111335616";
        String stageId = "656052818036932";
        String customerStatus = customerEntity.getCustomer_status();
        if (StringUtils.isEmpty(customerStatus) || !CommonConstants.TRANSFER_SUCCESS.equals(customerStatus)) {
            travelId = null;
            stageId = null;
        }
        CustomerImportRequest request = CustomerImportRequest.of(travelId, stageId, null, customerEntity.getTanMaCustomerId(), fields);
        log.info("request: {}", JSONUtil.toJsonStr(request));

        return JSONUtil.toJsonStr(request);
    }


    public void syncOrder2TanMa() {

        AtomicLong res = new AtomicLong(0);

        String uri = "/external/order/batchImport";
        String channelId = "202505211010304759";
        String channelName = "校管家成单客户";
        String shopId = "202504211042000";
        String shopName = "过往客户单";

        // todo 常熟校
//        String campusId = "fc540af1-038e-4614-bf0e-cd3ab437730d";
        // ======================================================
        // todo 北雅国际教育-龙湖校
//        String campusId = "05d743fd-bed4-45ad-9bcd-a7685bc829ed";

        // todo 北雅国际教育-市区校
//        String campusId = "77542ad3-abf7-4d82-a2a2-53aaab228675";

        // todo 北雅国际教育-尼盛校
//        String campusId = "7adf4f36-f871-41d5-902f-efb0f2ab38f9";

        // todo 北雅国际教育-新光校
        String campusId = "55950eda-e3b7-417d-a602-bfe4c0308963";

        // todo 北雅国际教育-张家港
//        String campusId = "c257468f-5b28-4aad-918e-3dd03f01c7cc";

        courseService.createQuery()
                     .fetch()
                     .collectMap(CourseEntity::getId, CourseEntity::getName)
                     .flatMapMany(courseMap -> {
                         return orderService.createQuery()
//                                 .where(ChargeEntity::getPhone, "18120172509")
                                 .where(OrderEntity::getCampus_id, campusId)
                                 .where(OrderEntity::getOrder_status, OrderStatusEnum.paid.getText())
                                     .fetch()
                                     .flatMap(orderEntity -> {
                                         String orderTime = DateFormatterUtils.format(orderEntity.getOrder_date());
                                         String payTime = DateFormatterUtils.format(orderEntity.getPayment_date());
                                         OrderRequest.Order order = OrderRequest.Order
                                                 .builder()
                                                 .channelId(channelId)
                                                 .channelName(channelName)
                                                 .shopId(shopId)
                                                 .shopName(shopName)
                                                 .mobile(orderEntity.getPhone())
                                                 .orderId(orderEntity.getOrder_code())
                                                 .orderStatus(OrderStatusEnum.closed.getStatus())
                                                 .orderTime(orderTime)
                                                 .payTime(payTime)
                                                 .build();
                                         List<Product> products = orderEntity.getProducts();
                                         if (products == null || products.isEmpty()) {
                                             return Mono.empty();
                                         }
                                         List<OrderRequest.Good> goods = products
                                                 .stream()
                                                 .map(product -> {
                                                     String productId = product.getProduct_id();
                                                     String courseName = courseMap.getOrDefault(productId, "");
                                                     Double unitPrice = product.getUnit_price();
                                                     Double amount = product.getAmount();
                                                     return OrderRequest.Good.of(courseName, unitPrice, amount);
                                                 })
                                                 .collect(Collectors.toList());
                                         OrderRequest orderRequest = OrderRequest
                                                 .builder()
                                                 .order(order)
                                                 .goods(goods)
                                                 .build();
                                         return Mono.just(orderRequest);
                                     })
                                     .buffer(100)
                                     .flatMap(orders -> {
                                         res.getAndAdd(orders.size());
                                         Map<String, Object> bodyMap = new HashMap<>();
                                         bodyMap.put("batchId", IDGenerator.UUID.generate());
                                         bodyMap.put("orderList", orders);
                                         String bodyStr = JSONUtil.toJsonStr(bodyMap);
                                         log.info("request: {}", bodyStr);
                                         return httpService.postForTanMaProduceOrder(uri, bodyStr, TanMaResponse.class);
//                                         return Mono.just(bodyStr);
                                     })
                                     .doOnNext(str-> {
                                         System.out.println("str = " + str);
                                     });
                     }).blockLast();

        System.out.println("总数量 = " + res.get());

    }


}
